<?php
/**
 * source 1: http://jsfiddle.net/bgrins/tzYbU/
 * source 2: http://www.codeproject.com/Articles/706869/jQueryUI-Sort-Example
 */
class SortableGridView extends CWidget {
    
    public $selector;
    public $options;
    public $processingUrl;
    public $params=array();

    private $_assetsUrl;

    public function init() {
        parent::init();
        if ($this->_assetsUrl === null) {
            $assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
            $this->_assetsUrl = Yii::app()->assetManager->publish($assetsDir);
        }
        $this->params['YII_CSRF_TOKEN']=Yii::app()->request->csrfToken;
    }

    public function run() {
        $params='';
        foreach($this->params as $key=>$value){
            $params.= '&'.$key.'='.$value;
        }
        Yii::app()->clientScript
                //->registerScriptFile($assetsUrl . '/jquery.ui.nestedSortable.js', CClientScript::POS_HEAD)
                ->registerScriptFile($this->_assetsUrl.'/jquery-ui.min.js', CClientScript::POS_END)
                ->registerScript(__CLASS__, ' 
				
                    $(document).ready(function(){

                        var fixHelper = function(e, ui) {
                            ui.children().each(function() {
                                $(this).width($(this).width());
                            });
                            return ui;
                        };

                        function handleReorderElements(){
                            var url = "'.$this->processingUrl.'";
                            var fieldData = $( "'.$this->selector.'" ).sortable( "serialize" );
                            //fieldData += "&action=reorderElements";
                            fieldData = fieldData +"'.$params.'";
                            
                            var posting = $.post( url, fieldData);
                            posting.done( function( data)
                              {
                              //reorderElementsResponse( data );
                              });
                        }

                        $("'.$this->selector.'").sortable({
                            helper: fixHelper,
                            cursor: "move",
                            stop: handleReorderElements,
                        }).disableSelection();
                    });

		', CClientScript::POS_END);
    }

}
